import 'dart:async';

import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/preferred_size.dart';
import 'package:flutter_elf/config/component_index.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class WebViewPage extends BaseWidget{
  final String  url;
  WebViewPage(this.url);

  @override
  BaseWidgetState<BaseWidget> getState() {
    // TODO: implement getState
    return WebViewPageState();
  }
}

class WebViewPageState extends BaseWidgetState<WebViewPage>{
  StreamSubscription<String> onUrlChanged;
  // WebView加载状态变化监听器
  StreamSubscription<WebViewStateChanged> onStateChanged;
  FlutterWebviewPlugin flutterWebViewPlugin = new FlutterWebviewPlugin();
  bool isLoadingCallbackPage = false;

  bool loading = true;
  @override
  void onCreate() {
    // TODO: implement onCreate
    super.onCreate();
    onStateChanged = flutterWebViewPlugin.onStateChanged.listen((WebViewStateChanged state){
      // state.type是一个枚举类型，取值有：WebViewState.shouldStart, WebViewState.startLoad, WebViewState.finishLoad
      switch (state.type) {
        case WebViewState.shouldStart:
        // 准备加载
          setState(() {
            loading = true;
          });
          break;
        case WebViewState.startLoad:
        // 开始加载
          break;
        case WebViewState.finishLoad:
        // 加载完成
          setState(() {
            loading = false;
          });
          if (isLoadingCallbackPage) {
            // 当前是回调页面，则调用js方法获取数据
            parseResult();
          }
          break;
        case WebViewState.abortLoad:
        // TODO: Handle this case.
          break;
      }
    });
  }
  parseResult(){

  }
  @override
  Widget buildView(BuildContext context) {
    // TODO: implement buildView
    return new WebviewScaffold(
      url:widget.url, // 登录的URL
      withZoom: true,  // 允许网页缩放
      withLocalStorage: true, // 允许LocalStorage
      withJavascript: true, // 允许执行js代码

    );
  }

  @override
  PreferredSizeWidget initAppbar() {
    // TODO: implement initAppbar
    return null;
  }

  @override
  void onDestroy() {
    onUrlChanged.cancel();
    onStateChanged.cancel();
    flutterWebViewPlugin.dispose();
    super.onDestroy();
  }

}